//
//  ResourcesViewController.m
//  CareGiver
//
//  Created by Guillermo Moral on 8/14/14.
//  Copyright (c) 2014 Humana. All rights reserved.
//

#import "ResourcesViewController.h"
#import "ResourcesViewController+Adapter.h"
#import "ResourceTableViewCell.h"
#import "UISearchBar+Additions.h"
#import <AddressBook/AddressBook.h>

#define searchContentOpen 80
#define searchContentClose 40

#define currentLocationLoc 237
#define currentLocationExpanded 303

#define defaulKeyword = @"health"

static CGFloat const kEspressoDescriptionTextFontSize = 12.0f;

static inline NSRegularExpression * NameRegularExpression() {
    static NSRegularExpression *_nameRegularExpression = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _nameRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"^\\w+" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    
    return _nameRegularExpression;
}

static inline NSRegularExpression * ParenthesisRegularExpression() {
    static NSRegularExpression *_parenthesisRegularExpression = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _parenthesisRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\\([^\\(\\)]+\\)" options:NSRegularExpressionCaseInsensitive error:nil];
    });
    
    return _parenthesisRegularExpression;
}

@interface ResourcesViewController ()

@property(nonatomic, assign)BOOL searchAnimation;
@property(nonatomic, assign)BOOL searchColapse;

@end


@implementation ResourcesViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.lastMessageRow = 9;
    [self configureNavigationBar];
    [self setup];

    ///////////////////////////////////////////////////////////////
    [self.searchKeyword updateStatus];
    [self.searchKeyword updateButtonColor:[UIColor whiteColor]];
}



-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self registerForChangeNotification];
    //[self expand];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self unregisterForChangeNotification];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self configureResourceListTable];
    [self loadResourcesData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setup {
    self.message.textColor = [UIColor grayColor];
    self.searchAddress.keyword = @"health";
    self.navigationController.navigationBar.barTintColor = [UIColor greenColor];
    self.navigationController.navigationBar.translucent = NO;
    [self loadResourcesData];
    
    UIImageView *i = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search.png"]];
    UIImageView *l = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"location.png"]];
    UIView *lView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22, 33)];
    
    [lView addSubview:i];
    
    i.frame = CGRectMake(lView.frame.size.width-i.frame.size.width,lView.frame.size.height*0.5-i.frame.size.height*0.5, i.frame.size.width, i.frame.size.height);
    
    UIView *rView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22, 33)];
    [rView addSubview:l];
    
     l.frame = CGRectMake(0,rView.frame.size.height*0.5-l.frame.size.height*0.5, l.frame.size.width, l.frame.size.height);

}

-(void)layoutSublayersOfLayer:(CALayer *)layer {
    
}

-(void)configureResourceListTable {
    self.tbl_resourceList.backgroundColor = [UIColor grayColor];
    self.tbl_resourceList.sectionFooterHeight =0;
    self.tbl_resourceList.sectionHeaderHeight =0;
}

# pragma  Observer

-(void)registerForChangeNotification {
    [self addObserver:self forKeyPath:@"crdServiceCallInProgress" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
}

-(void)unregisterForChangeNotification {
    [self removeObserver:self forKeyPath:@"crdServiceCallInProgress"];
}

-(void)configureNavigationBar {
    //[self displayLeftBarButtonItemBackButtonIcon];
    //[self displayNavigationTitle:@"Resources"];
}


# pragma TableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.resourcesData count];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}
/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
*/

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ResourceTableViewCell *resourceTableViewCell = [self.tbl_resourceList dequeueReusableCellWithIdentifier:@"resourceCell" forIndexPath:indexPath];
    ResourceModel *resModel = [self.resourcesData objectAtIndex:indexPath.row];
    
    [resourceTableViewCell configureTitle:resModel.organization summary:resModel.address1 state:resModel.status distance:@""];
    resourceTableViewCell.selectionStyle = UITableViewCellSeparatorStyleNone;
    
    return resourceTableViewCell;
}


// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Tocaste un celda");
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  [self loadMoreResourcesData];
}

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Stop Indicator
}
# pragma KVO override

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self && [keyPath isEqualToString:@"crdServiceCallInProgress"]) {
        if(![[change objectForKey:NSKeyValueChangeNewKey] boolValue]) {
            [self.tbl_resourceList reloadData];
        }
    }
}

# pragma Core Location

// Take State and Region
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Cant Determite Location");
}

// Take State and Region
-(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {
    NSLog(@"I have the Location");
}

# pragma - Public Method



#pragma - TextField

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self.searchKeyword updateStatus];
    if(self.searchColapse && !self.searchAnimation) {
        [self performSelectorOnMainThread:@selector(expand) withObject:nil waitUntilDone:YES];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    //[self collapse];
    return YES;
}

# pragma - SearchBar

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [self.searchKeyword updateStatus];
    self.searchKeyword.showsCancelButton = YES;
    [self.searchKeyword updateButtonColor:[UIColor whiteColor]];
    
}


# pragma - Search Colapse / Expanded

-(void)expand {
    self.searchColapse = NO;
    self.searchAnimation = YES;
    [UIView animateWithDuration:.1f animations:^
    {
        self.veilView.hidden = NO;
    } completion:^(BOOL finished) {
        
        self.searchAnimation = NO;
    }];
}

-(void)collapse {
    self.searchColapse = YES;
    self.searchAnimation = YES;
    [UIView animateWithDuration:.1f animations:^
     {
         self.veilView.hidden = YES;
         
     } completion:^(BOOL finished)
     {
         self.searchAnimation = NO;
     }];
}

# pragma  - Segue

-(void)prepareViewController:(id)vc forSegue:(NSString*)segueIdentifer fromIndexPath:(NSIndexPath*)indexPath {
    if([vc isKindOfClass:[ResourceDetailViewController class]]) {
        ResourceDetailViewController *rVC = (ResourceDetailViewController*)vc;
        [rVC updateCurrentLocation:[self.resourcesData objectAtIndex:indexPath.row]];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSIndexPath *indexPath = nil;
    
    if([sender isKindOfClass:[UITableViewCell class]]) {
        indexPath = [self.tbl_resourceList indexPathForCell:sender];
    }
    
    [self prepareViewController:segue.destinationViewController
                       forSegue:segue.identifier
                  fromIndexPath:indexPath];
}

#pragma mark - TTTAttributedLabelDelegate

- (void)attributedLabel:(__unused TTTAttributedLabel *)label
   didSelectLinkWithURL:(NSURL *)url
{
    [[[UIActionSheet alloc] initWithTitle:[url absoluteString] delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Open Link in Safari", nil), nil] showInView:self.view];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:actionSheet.title]];
}



#pragma mark - Create a Contact



@end
